<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" label-width="68px">
      <el-form-item label="企业账号" prop="username">
        <el-input v-model="queryParams.username" placeholder="请输入企业账号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="企业名称" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入企业名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="企业状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择企业状态" clearable>
          <el-option v-for="item in statusArray" :key="item" :label="item" :value="item" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button v-hasPermi="['system:enterprise:list']" type="primary" icon="el-icon-search" size="small"
          @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="small" @click="resetQuery">重置</el-button>
        <el-button v-hasPermi="['system:enterprise:add']" type="primary" plain icon="el-icon-plus" size="small"
          @click="handleAdd">新增</el-button>
        <el-button v-hasPermi="['system:enterprise:delete']" type="danger" plain icon="el-icon-delete" size="small"
          :disabled="multiple" @click="handleDelete">
          批量删除
        </el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button v-hasPermi="['system:enterprise:import']" type="info" plain icon="el-icon-upload2" size="small"
          @click="handleImport">导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button v-hasPermi="['system:enterprise:export']" type="warning" plain icon="el-icon-download" size="small"
          @click="handleExport">导出</el-button>
      </el-col>
    </el-row>

    <el-table style="margin-top: 20px;" v-loading="loading" :data="enterpriseList"
      @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="45" align="center" />
      <el-table-column label="企业账号" align="center" prop="username" />
      <el-table-column label="企业名称" align="center" prop="name" />
      <el-table-column label="企业电话" align="center" prop="phoneNumber" />
      <el-table-column label="企业邮箱" align="center" prop="email" />
      <el-table-column label="企业状态" align="center" prop="status">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.status" active-value="启用" inactive-value="禁用"
            @change="handleStatusChange(scope.row)"></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime">
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button v-hasPermi="['system:enterprise:update']" size="mini" type="text" icon="el-icon-edit"
            @click="handleUpdate(scope.row)">修改</el-button>
          <el-button v-hasPermi="['system:enterprise:delete']" size="mini" type="text" icon="el-icon-delete"
            @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination style="float: right;margin-top: 20px;" @size-change="handleSizeChange"
      @current-change="handleCurrentChange" background :current-page="queryParams.currentPage"
      :page-sizes="[5,10,50,100]" :page-size="queryParams.pageSize" layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>

    <!-- 添加或修改企业配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="账号" prop="username">
              <el-input v-model="form.username" placeholder="请输入账号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="密码" prop="password">
              <el-input :disabled="title=='修改企业'" v-model="form.password" placeholder="请输入密码" type="password"
                show-password />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入企业名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号" prop="phoneNumber">
              <el-input v-model="form.phoneNumber" placeholder="请输入手机号" maxlength="11" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="form.email" placeholder="请输入邮箱" maxlength="50" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="角色" prop="roleIds">
              <el-select v-model="form.roleIds" multiple placeholder="请选择角色">
                <el-option v-for="item in roleOptions" :key="item.id" :label="item.name" :value="item.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="备注">
              <el-input v-model="form.remark" placeholder="请输入内容" maxlength="255"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态">
              <el-radio-group v-model="form.status">
                <el-radio v-for="item in statusArray" :key="item" :label="item">
                  {{item}}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 企业导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers" :action="upload.url"
        :disabled="upload.isUploading" :before-upload="handleFileUploadProgress" :on-success="handleFileSuccess"
        :auto-upload="false" :drag="true">
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <span>仅允许导入xls、xlsx格式文件。</span>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {
    listEnterprise,
    getEnterprise,
    deleteEnterprise,
    addEnterprise,
    updateEnterprise
  } from "@/api/system/enterprise";
  import {
    getToken
  } from "@/utils/auth";
  import {
    listRole
  } from "@/api/system/role";

  export default {
    name: "Enterprise",
    data() {
      return {
        loading: true,
        statusArray: ['启用', '禁用'],
        // 角色选项
        roleOptions: [],
        // 选中数组
        ids: [],
        // 非多个禁用
        multiple: true,
        // 总条数
        total: 0,
        // 企业表格数据
        enterpriseList: [],
        // 弹出层标题
        title: "",
        // 企业导入参数
        upload: {
          // 是否显示弹出层（用户导入）
          open: false,
          // 弹出层标题（用户导入）
          title: "",
          // 是否禁用上传
          isUploading: false,
          // 设置上传的请求头部
          headers: {
            Authorization: getToken()
          },
          // 上传的地址
          url: process.env.VUE_APP_BASE_API + "/system/user/enterprise/import"
        },
        // 是否显示弹出层
        open: false,
        // 查询参数
        queryParams: {
          currentPage: 1,
          pageSize: 10,
          username: undefined,
          name: undefined,
          status: undefined
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          username: [{
            required: true,
            message: "账号不能为空",
            trigger: "blur"
          }],
          name: [{
            required: true,
            message: "名称不能为空",
            trigger: "blur"
          }],
          password: [{
            required: true,
            message: "密码不能为空",
            trigger: "blur"
          }],
          email: [{
            type: "email",
            required: true,
            trigger: "blur",
            message: "请输入正确格式的邮箱"
          }],
          roleIds: [{
            required: true,
            message: "角色不能为空",
            trigger: "change"
          }]
        }
      };
    },
    created() {
      this.getList();
    },
    methods: {
      handleStatusChange(row) {
        let text = row.status
        this.$confirm('确认要"' + text + '""' + row.name + '"吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          updateEnterprise(row).then(() => {
            this.getList()
            this.$message.success(text + '成功')
          }).catch(() => {
            this.getList()
          })
        }).catch(() => {
          this.getList()
        })
      },
      handleCurrentChange(val) {
        this.queryParams.currentPage = val;
        this.getList();
      },
      handleSizeChange(val) {
        this.queryParams.pageSize = val;
        this.getList();
      },
      /** 查询企业列表 */
      getList() {
        this.loading = true
        listEnterprise(this.queryParams).then(response => {
          this.enterpriseList = response.data.records;
          this.total = response.data.total;
          this.loading = false
        });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          id: undefined,
          username: undefined,
          name: undefined,
          phoneNumber: undefined,
          email: undefined,
          remark: undefined,
          password: undefined,
          status: '禁用',
          roleIds: []
        };
        this.$refs['queryForm'].resetFields();
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.currentPage = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.$refs['queryForm'].resetFields();
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.multiple = !selection.length
      },
      getRoleList() {
        listRole({
          status: '启用'
        }).then((response) => {
          this.roleOptions = response.data.records
        })
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.getRoleList();
        this.open = true;
        this.title = "新增企业";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        this.getRoleList();
        getEnterprise(row.id).then(response => {
          this.form = response.data;
          this.open = true;
          this.title = "修改企业";
        });
      },
      /** 提交按钮 */
      submitForm: function() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.id != undefined) {
              updateEnterprise(this.form).then(response => {
                this.$message.success("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              addEnterprise(this.form).then(response => {
                this.$message.success("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        let ids = row.id || this.ids
        this.$confirm(`此操作删除id为【${ids}】的数据, 是否继续?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          deleteEnterprise(ids).then(res => {
            this.getList();
            this.$message.success("删除成功");
          })
        }).catch(() => {});
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download('system/user/enterprise/export', {
          ...this.queryParams
        }, `企业表.xlsx`)
      },
      /** 导入按钮操作 */
      handleImport() {
        this.upload.title = "企业导入";
        this.upload.open = true;
      },
      // 文件上传中处理
      handleFileUploadProgress(file) {
        const suffix = file.name.substring(file.name.lastIndexOf(".") + 1);
        if (suffix != "xls" && suffix != "xlsx") {
          this.$message.error('上传文件只能是xls、xlsx格式');
          return false;
        }
        this.upload.isUploading = true;
        return true;
      },
      // 文件上传成功处理
      handleFileSuccess(response) {
        this.upload.open = false;
        this.upload.isUploading = false;
        this.$refs.upload.clearFiles();
        this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response
          .message + "</div>", "导入结果", {
            dangerouslyUseHTMLString: true
          });
        this.getList();
      },
      // 提交上传文件
      submitFileForm() {
        this.$refs.upload.submit();
      }
    }
  };
</script>
